#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 带控制台调试窗口
# pyinstaller -F Simplify.py

# 不带控制台
# pyinstaller -F -w Simplify.py

# ICON
# pyinstaller -F -i favicon.ico Zilean.py

# ICON 不带控制台
# pyinstaller -F -w -i favicon.ico Zilean.py

from email import utils
import json
import http.client  #修改引用的模块
import hashlib
from msilib import Table
from operator import index
from tokenize import group    #修改引用的模块
from urllib import parse
import random
import os
import Utils
from Log import Debug
# import time
# import threading
# import gevent
# from gevent import monkey; monkey.patch_all()
from Translator import Translation
i18ns = {}

try:

    Debug.Log("读表开始...")
    fileName = "./Language.txt"
    lans = None
    with open(fileName, 'r', encoding='utf-8') as fp:
        lans = fp.readlines()
    fp.close()
    
    Debug.Log("建表&遍历需要翻译的多语言组...")
    needTranslates = []
    for lan in lans:
        params = lan.split('\t')
        if None == params or len(params) < 4 or "Key" in params[0]:
            continue
        key = params[0]
        lines = i18ns[key] = []
        need = False
        for i in range(3,len(params)):
            field = params[i]
            lines.append(field)
            if '' == field:
               need = True
        if need:
            needTranslates.append(key)

    # Debug.Log("翻译前最后一次整理")
    # task_list = []
    # for need in needTranslates:
    #     group = i18ns[need]
    #     for i in range(1,len(group)):
    #         if group[i] == "":
    #             task = gevent.spawn(Translater, group[0], 'zh', "cht" if i == 1 else "en",need)
    #             task_list.append(task)
    # Debug.Log("开启协程&执行任务列表中的所有任务...")
    # gevent.joinall(task_list)


    Debug.Log("组装待翻译的语言...")
    toEn = []
    toCht = []
    text2group = {}
    for need in needTranslates:
        group = i18ns[need]
        for i in range(1,len(group)):
            if group[i] == "" or group[i] == "\n":
                if i == 1:
                    toCht.append(group[0])
                else:
                    toEn.append(group[0])
                text2group[group[0]] = group

    Debug.Log("翻译英语组...")
    enTexts,enWorlds = Translation(toEn,'zh','en')
    Debug.Log("英语组翻译结果数据转换...")
    for world in enWorlds:
        group = text2group[world.GetText()]
        group[2] = world.GetTranslateText()
    
    Debug.Log("翻译繁体组...")
    chtTexts,chtWorlds = Translation(toCht,'zh','cht')
    Debug.Log("繁体组翻译结果数据转换...")
    for world in chtWorlds:
        group = text2group[world.GetText()]
        group[1] = world.GetTranslateText()

    Debug.Log("将多语言表输出csv格式txt")
    newLanguageText = "Key\tType\tDesc\tChinese (Simplified)\tChinese (Traditional)\tEnglish\n"
    for key in i18ns.keys():
        group = i18ns[key]
        lineText = f"{key}\tText\t \t{group[0]}\t{group[1]}\t{group[2]}"
        newLanguageText += lineText
    Utils.writeInFile("NewLanguage.txt",newLanguageText)

    Debug.Log("新增列表:")
    for need in needTranslates:
        group = i18ns[need]
        print(need,group)

    Debug.Log("转换完成...")
except Exception as e:
    print(e)
    Debug.LogExcept()
finally:
    Debug.Output()